import { api } from '@T2/plugins/env-config.ts'; //环境变量
import { deviceApi, unitApi, elementApi } from '@T2/service/api.ts';
import { Base64 } from 'js-base64'; 

const hostStr = {
  development: 'bimfaceHost',
  production: 'https://api.bimface.com',  //其实跨域无效
}[import.meta.env.MODE];
const appKey = 'JmACbq9FR1jHO0eB6hfkbqFwjv4M2XCG', appSecret = 'VakIH0eLXmS7DP9Uv2mO9WcsLiYjp130';

let accessToken = 'cn-15ec3faf-b232-479d-93da-9c502998c137';  //expireTime:  "2024-03-06 16:41:01";
(function getAccessToken() {
  if (import.meta.env.MODE == 'development' && !accessToken) {
    fetch(`${hostStr}/oauth2/token`, {
      method: 'post',
      headers: {
        'Authorization': "Basic" + " " + Base64.encode(appKey + ":" + appSecret),
        "Content-Type": "application/json",
      }
    })
    .then(res => res.json())
    .then(res => {
      if (res?.data?.token) {
        accessToken = res.data.token;
      }
    });
  }
})();

export async function getViewer3D(fileid, domID) {
  let viewToken = '', viewer3D = null;
  await fetch(`${api}/ruoshui/bimface/rest/model/?ordering=-create_time`, {
    method: 'get',
    headers: {}
  })
  .then(res => res.json())
  .then(res => {
    let model = res?.results?.find(i => i.fileid === fileid) || {};
    viewToken = model.viewtoken;
  });
  
  // Function to load Bimface SDK and initialize the app
  async function loadBimfaceSDKLoader() {
    return new Promise((resolve, reject) => {
      let e = document.createElement('script');
      e.type = 'module';
      e.charset = 'utf-8';
      e.src = 'https://static.bimface.com/api/BimfaceSDKLoader/BimfaceSDKLoader@latest-release.js';
      e.onload = () => {
        resolve();
      };
      e.onerror = () => {
        reject(new Error('Failed to load Bimface SDK'));
      };
      document.body.appendChild(e);
    });
  }
  
  // 加载SDK后初始化应用程序的函数
  function initApp(elementID) {
    return new Promise((resolve, reject) => {
      function successCallback() {
        let webAppConfig = new Glodon.Bimface.Application.WebApplication3DConfig();
        webAppConfig.Buttons = [];  //隐藏底部工具栏
        webAppConfig.Toolbars = []; //隐藏左上角筛选树
        webAppConfig.domElement = document.getElementById(elementID);
        webAppConfig.globalUnit = Glodon.Bimface.Common.Units.LengthUnits.Millimeter; // 设置全局单位
        let app = new Glodon.Bimface.Application.WebApplication3D(webAppConfig);
        app.addView(viewToken);
        viewer3D = app.getViewer();
        resolve();
      }
  
      function failureCallback(error) {
        reject(error);
      }
  
      let loaderConfig = new BimfaceSDKLoaderConfig();
      loaderConfig.viewToken = viewToken;
      BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
    });
  }
  
  // 检查Glodon是否已加载，如果未加载，请加载
  if (!window.Glodon) {
    await loadBimfaceSDKLoader();
  }
  
  // 初始化应用程序
  await initApp(domID);
  
  // 初始化完成后返回viewToken和应用程序
  return viewer3D;
}

export async function getBasicUDS() {
  function getUnitList() {
    return new Promise((resolve, reject) => {
      unitApi({
        method: 'get',
        params: {
          ordering: 'code',
        },
      }).then(res => {
        resolve(res?.results || []);
      }).catch(e => {
        reject(e);
      });
    }) 
  }
  function getDeviceList() {
    return new Promise((reslove, reject) => {
      deviceApi({
        method: 'get',
        params: {
          ordering: '-create_time',
        },
      }).then(res => {
        reslove(res?.results || []);
      }).catch(e => {
        reject(e);
      });
    })
  }
  function getCodeElementList() {
    return new Promise((reslove, reject) => {
      elementApi({
        method: 'get',
        params: {
          ordering: 'code',
          code__isnull: false,
        },
      }).then(res => {
        reslove(res?.results || []);
      }).catch(e => {
        reject(e);
      });
    })
  }
  let units = [], devices = [], elements = [];
  await Promise.all([getUnitList(), getDeviceList(), getCodeElementList()]).then(res => {
    units = res[0];
    devices = res[1].map(i => {
      return {id: i.id, name: i.name, code: i.code, unit: i.unit}
    });
    /* 加"e_"前缀，因为下文会和devices整合 */
    elements = res[2].map(i => {
      return {
        e_id: i.id,
        e_code: i.code,
        e_elementid: i.elementid,
        e_sensors: i.sensors.map(j => { return { id: j }}),
      }
    });
    elements = elements.filter(i => i.e_sensors.length);
  });
  /* 整合devices和elements */
  let eleMap = {};
  for (let i = 0; i < elements.length; i++) {
    eleMap[elements[i].e_code] = elements[i];
  }
  let newDE = [];
  for (let i = 0; i < devices.length; i++) {
    let dItem = devices[i];
    let eItem = eleMap[dItem.code];
    // 如果匹配到，将elements对象的属性加上“e_”前缀，合并到devices对象中
    if (eItem) {
      let mergedObject = Object.assign({}, dItem, eItem);
      newDE.push(mergedObject);
    }
  }
  
  /* 将newDE存放到units里 */
  let unitsMap = {};
  for (let i = 0; i < units.length; i++) {
    units[i].deChildren = [];
    unitsMap[units[i].id] = units[i];
  }
  for (let j = 0; j < newDE.length; j++) {
    let deItem = newDE[j];
    let uItem = unitsMap[deItem.unit];
  
    if (uItem) {
      uItem.deChildren.push(deItem);
    }
  }
  units = units.filter(i => i.deChildren.length);
  return units;
}

export async function getElementByCode(fileid) {
  /* 获取设备列表 */
  // let deviceList = [];
  // await deviceApi({
  //   method: 'get',
  //   params: {
  //     page: 1,
  //     project: 155,
  //   },
  // }).then(res => {
  //   deviceList = res?.results || [];
  // });
  
  // let elementIds = [];
  // let obj = {
  //   targetType: "file",
  //   targetIds: fileid,
  //   query: {
  //     match: {
  //       "camera": 'C10',
  //     }
  //   }
  // };
  // fetch(`${hostStr}/data/v2/query/elementIds`, {
  //   method: 'POST',
  //   headers: {
  //     'Authorization': "Bearer" + " " + accessToken,
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify(obj)
  // })
  //   .then(res => res.json())
  //   .then(res => {
  //     if (res?.data?.length) {
  //       elementIds = res.data[0].elementIds;
  //     }
  //   });
  
  // let nums = 0;
  // getElems(nums);
  // function getElems(ind) {
  //   if (ind < deviceList.length) {
  //     setTimeout(() => {
  //       let obj = {
  //         targetType: "file",
  //         targetIds: fileid,
  //         query: {
  //           match: {
  //             "deviceCode": deviceList[ind].code,
  //           }
  //         }
  //       };
  //       fetch(`${hostStr}/data/v2/query/elementIds`, {
  //         method: 'POST',
  //         headers: {
  //           'Authorization': "Bearer" + " " + accessToken,
  //           "Content-Type": "application/json",
  //         },
  //         body: JSON.stringify(obj)
  //       })
  //         .then(res => res.json())
  //         .then(res => {
  //           if (res?.data?.length) {
  //             elementIds = res.data[0].elementIds;
  //           }
  //           nums ++;
  //           getElems(nums);
  //         });
        
  //     }, 500);
  //   }
  // }
}
